#include "taskeditor.h"
#include "ui_taskeditor.h"



#include <QFile>
#include <QResource>
#include <QLabel>
#include <QPicture>
#include <QMessageBox>
#include <QInputDialog>

TaskEditor::TaskEditor(QWidget *parent) :
    QWidget(parent),
    m_ui(new Ui::TaskEditor)
{
    m_ui->setupUi(this);
    db = new CDBProvider("",this);
    textEditorTask = new TextEdit(this);
    textEditorTask->setEnabled(false);
    textEditorHelper = new TextEdit(this);
    m_ui->gridLayout->addWidget(textEditorTask,0,0);
    m_ui->tabWidget->removeTab(0);
    AnswerEditVariant *aev =new AnswerEditVariant(this);
    aev->textEditor = new TextEdit(this);
    aev->getGrid()->addWidget(aev->textEditor);
    aev->setEnabled(false);
    answerEditor = aev;
    m_ui->tabWidget->setTabText(0,trUtf8("Шаблон ответа"));
    m_ui->tabWidget->insertTab(0,aev,trUtf8("Варианты ответов"));
    loadTree();
}

TaskEditor::~TaskEditor()
{
    delete m_ui;
    delete db;
}

void TaskEditor::changeEvent(QEvent *e)
{
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void TaskEditor::on_addCatalog_clicked()
{
    QTreeWidgetItem *i = new QTreeWidgetItem(1);
    QString name = "Раздел";
    QTreeWidgetItem *ci = m_ui->treeWidget->currentItem();

    if(ci->text(2)=="task")ci = ci->parent();
    bool task = (ci->text(2)=="cat_w_task");
    if(!task && (ci->childCount() == 0) && (ci->text(2)!="topCat"))
        task = (QMessageBox::question(this,trUtf8("Вопрос"),trUtf8("каталог пуст,\n начать в нем создавать задания?"),QMessageBox::Yes,QMessageBox::No)==QMessageBox::Yes);
    if(!task){
        name = QInputDialog::getText(this,trUtf8("Введите"),trUtf8("новое название раздела:"),QLineEdit::Normal,trUtf8("Раздел"),&task);
        if(!task)return;
        i->setIcon(0,QIcon(":/images/win/fileopen.png"));
        i->setText(2,"cat");
    }else{
        name = trUtf8("Задание №")+QString::number(ci->childCount()+1);
        i->setData(0,Qt::UserRole,QVariant(QString("")));
        i->setIcon(0,QIcon(":/images/win/filenew.png"));
        i->setText(2,"task");
        if(ci->childCount() > 0)i->setText(3,QString::number(ci->child(ci->childCount()-1)->text(3).toInt()+1));
        else i->setText(3,QString::number(0));
        ci->setText(2,"cat_w_task");
    }
    i->setText(0,name);
    if(ci == NULL)m_ui->treeWidget->addTopLevelItem(i);
    else {
        ci->addChild(i);
        ci->setExpanded(true);
    }
    db->saveTreeWidgetItemToDB(i);
}

void TaskEditor::on_deleteCatalog_clicked()
{
    QTreeWidgetItem *ci = m_ui->treeWidget->currentItem();
    if(ci->text(2).indexOf("topCat")!=-1)return;
    db->wait = true;
    if(QMessageBox::question(this,trUtf8("Вопрос"),trUtf8("Вы действительно хотите удалить раздел\nвместе с его содержимым?"),QMessageBox::Yes,QMessageBox::No)==QMessageBox::Yes){
         db->deleteItemsFromDB(ci->takeChildren());
         db->deleteItemFromDB(ci);
         QTreeWidgetItem *pi = ci->parent();
         if(pi)
             pi->takeChild(pi->indexOfChild(ci));
         else
             m_ui->treeWidget->takeTopLevelItem(m_ui->treeWidget->indexOfTopLevelItem(ci));
         m_ui->treeWidget->setCurrentItem(pi);
    }    
    db->wait =false;
}

void TaskEditor::loadTree(){    
    db->wait=true;
    QTreeWidgetItem * i = new QTreeWidgetItem();
    i->setText(0,trUtf8("Разделы"));
    i->setIcon(0,QIcon(":/images/mac/fileopen.png"));
    i->setText(1,"0");
    i->setText(2,"topCat");
    m_ui->treeWidget->clear();
    m_ui->treeWidget->addTopLevelItem(i);
    i->addChildren(db->getChieldFromDB(0));
    i->setExpanded(true);
    db->wait = false;
}

void TaskEditor::on_renameCatalog_clicked()
{
    QTreeWidgetItem *ci = m_ui->treeWidget->currentItem();
    if(ci == NULL)return;
    else {
        ci->setText(0,QInputDialog::getText(this,trUtf8("Переименовать"),trUtf8("введите новое имя раздела:"),QLineEdit::Normal,ci->text(0)));
    }
}



void TaskEditor::saveToDB(){
    saveTreeToDB();
}

void TaskEditor::saveTreeToDB(){
    db->wait = true;
    for(int i = 0;  i < m_ui->treeWidget->topLevelItemCount(); ++i){
        QTreeWidgetItem * it = m_ui->treeWidget->topLevelItem(i);
        if(!db->saveChieldToDB(it->takeChildren(),it->text(1).toInt())){
            QMessageBox::warning(this,trUtf8("Ошибка"),trUtf8("Сохранение не произошло"));
            break;
        }else
            db->saveTreeWidgetItemToDB(it);
    }
    db->wait = false;
}

void TaskEditor::saveDataToDB(){

}

void TaskEditor::on_saveToDB_clicked()
{
    saveToDB();
    loadTree();
    if(m_ui->checkBox->checkState()==Qt::Checked)
            m_ui->treeWidget->expandAll();
}

void TaskEditor::on_treeWidget_itemClicked(QTreeWidgetItem* item, int column)
{

}

void TaskEditor::on_treeWidget_itemCollapsed(QTreeWidgetItem* item)
{

}

void TaskEditor::on_treeWidget_currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous)
{

    textEditorTask->setEnabled(false);
    //answerEditor->setEnabled(false);
    if(previous)
        if(previous->text(2)=="task"){
            previous->setData(0,Qt::UserRole,QVariant(textEditorTask->getHtmlText()));
        }
    textEditorTask->fileNew(true);
    if(!current->data(0,Qt::UserRole).isNull()){
        textEditorTask->setHtmlText(current->data(0,Qt::UserRole).toString());
        textEditorTask->setEnabled(true);
        setAnswer(current->text(1).toInt());
    }

}

void TaskEditor::on_showEditor_clicked()
{
    textEditorHelper->show();
}

void TaskEditor::on_treeWidget_itemChanged(QTreeWidgetItem* item, int column)
{
    QTreeWidgetItem * parent = item->parent();
    int index = 0;
    if(parent) index = parent->text(1).toInt();
    db->saveTreeWidgetItemToDB(item,index);
}

void TaskEditor::on_pushButton_clicked(bool checked)
{
   m_ui->lineEdit->setEnabled(!checked);
}

void TaskEditor::setAnswer(int idTask){
    QString tempAnswer = db->getTemplateAnswer(idTask);
    if(!tempAnswer.isEmpty()){
         m_ui->templateAnswer->activateWindow();         
         m_ui->lineEdit->setText(tempAnswer);
         m_ui->tabWidget->setCurrentIndex(1);
    }else{
        answerEditor->setEnabled(true);        
        answerEditor->setIdTask(idTask);
        m_ui->tabWidget->setCurrentIndex(0);
        m_ui->lineEdit->clear();
    }
    activateTemplateAnswer();
}

void TaskEditor::on_lineEdit_lostFocus()
{
    db->saveTemplateAnswer(m_ui->treeWidget->currentItem()->text(1).toInt(),m_ui->lineEdit->text());
    activateTemplateAnswer();
}

void TaskEditor::on_pushButton_2_clicked()
{
    m_ui->lineEdit->clear();
    db->saveTemplateAnswer(m_ui->treeWidget->currentItem()->text(1).toInt(),"");
    activateTemplateAnswer();
}

void TaskEditor::on_checkBox_clicked(bool checked)
{
    if(checked)
        m_ui->treeWidget->expandAll();
    else
        m_ui->treeWidget->collapseAll();
}

void TaskEditor::activateTemplateAnswer(){
    if(!m_ui->lineEdit->text().isEmpty()){        
        m_ui->lineEdit->setEnabled(false);
        m_ui->pushButton->setChecked(false);
        m_ui->tabWidget->widget(0)->setEnabled(false);
        m_ui->tabWidget->setTabEnabled(0,false);
    }else{
        m_ui->lineEdit->setEnabled(true);
        m_ui->pushButton->setChecked(true);
        m_ui->tabWidget->widget(0)->setEnabled(true);
        m_ui->tabWidget->setTabEnabled(0,true);
    }
}

void TaskEditor::on_pushButton_4_clicked()
{
    QTreeWidgetItem *p = m_ui->treeWidget->currentItem()->parent();
    if(p->text(2) != "cat_w_task") return;
    int index = p->indexOfChild(m_ui->treeWidget->currentItem());
    if(p->childCount()>index+1){        
        QTreeWidgetItem *c  = p->takeChild(index);                
        db->taskSetOrder(c->text(1).toInt(),c->text(3).toInt()+1);
        p->insertChild(index+1,c);
        m_ui->treeWidget->setCurrentItem(c);
    }

}

void TaskEditor::on_pushButton_3_clicked()
{
    QTreeWidgetItem *p = m_ui->treeWidget->currentItem()->parent();
    if(p->text(2) != "cat_w_task") return;
    int index = p->indexOfChild(m_ui->treeWidget->currentItem());
    if(index>0){        
        QTreeWidgetItem *c  = p->takeChild(index);                
        db->taskSetOrder(c->text(1).toInt(),c->text(3).toInt()-1);
        p->insertChild(index-1,c);        
        m_ui->treeWidget->setCurrentItem(c);
    }    
}

void TaskEditor::on_btnSetOrders_clicked()
{
    this->cursor().setShape(Qt::WaitCursor);
    QTreeWidgetItem *p = m_ui->treeWidget->currentItem();
    setOrders(p);
    this->cursor().setShape(Qt::ArrowCursor);
}

void TaskEditor::setOrders(QTreeWidgetItem * c){
    if(c){
        if(c->text(2) == "task")
                 setOrders(c->parent());
        else {
            bool change = false;
            for(int i =0; i < c->childCount();++i){
                QTreeWidgetItem *ch = c->child(i);
                if(change =(ch->text(2)=="task")){
                    db->taskSetOrder(ch->text(1).toInt(),i+1);
                }else
                    setOrders(ch);

            }
            if(change){
                for(int i =c->childCount()-1; i >=0 ;--i)
                    delete(c->takeChild(i));
                c->addChildren(db->getTaskChieldFromDB(c->text(1).toInt()));
            }
        }
    }
}
